package show.marvelous.domain.chessgame.repository;

import cn.hutool.core.util.IdUtil;
import java.util.Collection;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import show.marvelous.domain.chessgame.aggregate.ChessGame;
import show.marvelous.domain.chessgame.aggregate.ChessGameBuilder;
import show.marvelous.domain.chessgame.aggregate.entity.DiceRecord;
import show.marvelous.domain.chessgame.aggregate.entity.MoveEvent;
import show.marvelous.domain.chessgame.constans.TakeOffStrategyEnum;
import show.marvelous.infrastructure.dao.chessgame.ChessGameDO;
import show.marvelous.infrastructure.dao.chessgame.ChessGameDOBuilder;
import show.marvelous.infrastructure.dao.chessgame.IChessGameDao;

/**
 * @author Kris
 * 2021/8/24
 */
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ChessGameRepository{

    private final IChessGameDao chessGameDao;
    private final DiceRecordRepository diceRecordRepository;
    private final MoveEventRepository moveEventRepository;

    public ChessGame initNewGame(){
        Long gameId = IdUtil.getSnowflake().nextId();
        ChessGame game = ChessGameBuilder.chessGame().id(gameId).takeOffStrategy(TakeOffStrategyEnum.SIX).build();
        ChessGameDO chessGameDO = ChessGameDOBuilder.chessGameDO().id(gameId).takeOffStrategy(game.getTakeOffStrategy())
                .build();
        chessGameDao.save(chessGameDO);
        return game;
    }

    public Optional<ChessGame> loadGame(long gameId){
        Optional<ChessGameDO> chessGameEntityOptional = chessGameDao.findById(gameId);
        if(!chessGameEntityOptional.isPresent()){
            return Optional.empty();
        }else{
            ChessGameDO chessGameDO = chessGameEntityOptional.get();
            Collection<DiceRecord> diceRecords = diceRecordRepository.listDiceRecord(gameId);
            Collection<MoveEvent> moveEvents = moveEventRepository.listMoveEvents(gameId);
            ChessGame game = ChessGameBuilder.chessGame().id(chessGameDO.getId())
                    .takeOffStrategy(chessGameDO.getTakeOffStrategy()).diceRecords(diceRecords).moveEvents(moveEvents)
                    .build();
            return Optional.of(game);
        }
    }
}
